/**
 *
 */
package cn.linlane.controller;

import cn.linlane.entity.exception.MyException;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.nio.file.AccessDeniedException;
import java.util.HashMap;
import java.util.Map;

/**
 * 控制器基类
 *
 * @author ShenHuaJie
 * @version 2016年5月20日 下午3:47:58
 */
public class BaseController {

	protected static final Logger logger = LoggerFactory.getLogger(BaseController.class);

	/** 设置响应代码 */
	private Map setMyMap(Map myMap, HttpServletResponse response, HttpStatus httpStatus) {
		response.setStatus(httpStatus.value());
		return setMyMap(myMap, null);
	}

	/** 设置响应代码 */
	private Map<String, Object> setMyMap(Map<String, Object> map, Object data) {
		if (data != null) {
			map.put("data", data);
		}
		map.put("timestamp", System.currentTimeMillis());
		return map;
	}

	/** 设置成功响应代码 */
	public Map setSuccessMap(Object data) {
		Map<String, Object> myMap = new HashMap<>(16);
		myMap.put("msg", "success!");
		return setMyMap(myMap, data );
	}

	/** 设置成功响应代码 */
	public Map setSuccessMap() {
		Map<String, Object> myMap = new HashMap<>(16);
		myMap.put("msg", "success!");
		return setMyMap(myMap, null );
	}

	/** 异常处理 */
	@ExceptionHandler(RuntimeException.class)
	public void exceptionHandler(HttpServletResponse response, Exception ex) throws Exception {
		logger.error(ex.getMessage(), ex);
		Map<String, Object> myMap = new HashMap<>(16);
		if (ex instanceof IllegalArgumentException) {
			if (StringUtils.isNotBlank(ex.getMessage())) {
				myMap.put("msg", ex.getMessage());
				myMap.put("errorCode", HttpStatus.BAD_REQUEST.value());
				setMyMap(myMap, response, HttpStatus.BAD_REQUEST);
			}
		} else {
			myMap.put("msg", "系统异常！");
			myMap.put("errorCode", HttpStatus.INTERNAL_SERVER_ERROR.value());
			setMyMap(myMap, response, HttpStatus.INTERNAL_SERVER_ERROR);
		}
		response.setContentType("application/json;charset=UTF-8");
		response.getOutputStream().write(JSON.toJSONBytes(myMap));
	}

	/** 自定义异常处理 */
	@ExceptionHandler(MyException.class)
	public void exceptionHandler(HttpServletResponse response, MyException ex) throws Exception {
		logger.error(ex.getMessage(), ex);
		Map<String, Object> myMap = new HashMap<>(16);
		myMap.put("msg", ex.getMessage());
		myMap.put("errorCode", ex.getErrorCode());
		setMyMap(myMap, response, ex.getHttpStatus());
		response.setContentType("application/json;charset=UTF-8");
		response.getOutputStream().write(JSON.toJSONBytes(myMap));
	}

}
